<template>
  <div>
    <el-form label-width="80px" class="search">
      <el-form-item label="设备编号">
        <el-input v-model="params.userName" clearable></el-input>
        <el-button icon="el-icon-search" type="primary" @click="search"
          >查询</el-button
        >
      </el-form-item>
    </el-form>
    <el-dialog
      ref="dialog"
      :title="title"
      :visible.sync="dialogVisible"
      width="600px"
      @close="close"
    >
      <el-form
        class="label"
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item label="人员名称:" prop="userName">
          <el-input
            v-model="ruleForm.userName"
            style="width: 90%"
            maxlength="5"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="角色:" prop="roleId">
          <el-select
            v-model="ruleForm.roleId"
            placeholder="请选择"
            style="width: 90%"
          >
            <el-option
              :label="item.roleName"
              :value="index + 2"
              v-for="(item, index) in role"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话:" prop="mobile">
          <el-input
            v-model="ruleForm.mobile"
            style="width: 90%"
            maxlength="11"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="负责区域:" prop="regionId">
          <el-select
            v-model="ruleForm.regionId"
            @change="changeRegionId"
            placeholder="请选择"
            style="width: 90%"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="(item, index) in areaList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像:" style="text-align: left" prop="image">
          <el-upload
            v-model="ruleForm.image"
            class="avatar-uploader"
            name="fileName"
            action="http://likede2-admin.itheima.net/likede/api/vm-service/sku/fileUpload"
            :show-file-list="false"
            :on-success="success"
            :before-upload="upload"
          >
            <img
              v-if="ruleForm.image"
              :src="ruleForm.image"
              class="avatar"
              style="width: 100px; height: 100px"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="状态:">
          <el-checkbox-group v-model="ruleForm.status">
            <el-checkbox label="是否启用" name="type"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <div class="main">
      <div class="title">
        <el-button
          icon="el-icon-circle-plus-outline"
          style="background-color: #ff732d; color: #fff"
          @click="addUser"
          >新建</el-button
        >
      </div>

      <div class="body">
        <template>
          <el-table style="width: 100%" :data="StaffData">
            <el-table-column label="序号" min-width="150" type="index">
            </el-table-column>

            <el-table-column label="人员名称" min-width="300" prop="userName">
            </el-table-column>

            <el-table-column
              label="归属区域"
              min-width="350"
              prop="regionName"
            ></el-table-column>
            <el-table-column
              label="角色"
              min-width="200"
              prop="role.roleName"
            ></el-table-column>
            <el-table-column
              label="联系电话"
              min-width="350"
              prop="mobile"
            ></el-table-column>

            <el-table-column label="操作" min-width="150">
              <template #default="scope">
                <el-button type="text" @click="update(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="text"
                  style="color: #ff5a5a"
                  @click="del(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>

      <div class="footer">
        <span
          >共{{ totalPage }}条记录&emsp;第{{ params.pageIndex }}/{{
            totalPage
          }}页</span
        >
        <div>
          <el-button
            size="small"
            @click="pre"
            :disabled="params.pageIndex === 1 ? true : false"
            >上一页</el-button
          >
          <el-button
            size="small"
            @click="next"
            :disabled="params.pageIndex === +totalPage ? true : false"
            >下一页</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getStaffList,
  delUser,
  getArea,
  getRole,
  addUser,
  updataUser
} from '@/api/staff' // addUser
export default {
  name: 'index-page',
  created () {
    this.getStaffList()
  },
  components: {},
  props: {},
  data () {
    function validMobile (str) {
      const reg = /^(?:(?:\+|00)86)?1\d{10}$/
      return reg.test(str)
    }
    const validateMobile = (rule, value, callback) => {
      if (!validMobile(value)) {
        callback(new Error('手机格式不对'))
      } else {
        callback()
      }
    }
    return {
      title: '',
      params: {
        pageIndex: 1,
        pageSize: 10,
        userName: ''
      },
      StaffData: [],
      totalPage: '',
      dialogVisible: false,
      ruleForm: {
        userName: '',
        roleId: '',
        mobile: '',
        regionId: '',
        regionName: '',
        status: '',
        image: ''
      },
      area: {
        pageIndex: 1,
        pageSize: 100000
      },
      ID: Number,
      areaList: [],
      role: [],
      rules: {
        userName: [
          { required: true, message: '请输入人员', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        roleId: [{ required: true, message: '请输入角色', trigger: 'change' }],
        mobile: [
          { required: true, trigger: 'blur', validator: validateMobile }
        ],
        regionId: [
          { required: true, message: '请输入活动名称', trigger: 'change' }
        ],
        image: [{ required: true, message: '请选择图片', trigger: 'change' }]
      }
    }
  },
  computed: {},
  methods: {
    /// //
    async getStaffList () {
      const res = await getStaffList(this.params)
      this.StaffData = res.currentPageRecords
      this.totalPage = res.totalPage
    },
    pre () {
      this.params.pageIndex = this.params.pageIndex - 1
      this.getStaffList()
    },
    next () {
      this.params.pageIndex = this.params.pageIndex + 1
      this.getStaffList()
    },
    search () {
      this.getStaffList()
    },
    async del (val) {
      const res = await delUser(val)
      console.log(res)
      this.$message.success('删除成功')
      this.getStaffList()
    },

    // 头像
    success (res, file) {
      this.ruleForm.image = res
    },
    upload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    changeRegionId (id) {
      console.log(111)
      const obj = this.areaList.filter((item) => item.id === id)
      this.ruleForm.regionName = obj[0].name
    },
    // 新增
    async addUser () {
      this.title = '新增人员'
      this.dialogVisible = true
      const res = await getArea(this.area)
      this.areaList = res.currentPageRecords
      const res1 = await getRole()
      this.role = res1
    },
    async submit () {
      try {
        await this.$refs.ruleForm.validate()

        if (this.title === '新增人员') {
          console.log(this.ruleForm)
          const res = await addUser(this.ruleForm)
          console.log(res)
          this.dialogVisible = false
          this.$message.success('添加成功')
        } else {
          console.log('这是提交')

          console.log(this.ruleForm.roleId)

          const res = await updataUser(this.ruleForm, this.ID)
          console.log(res)
          this.$message.success('修改成功')
          this.dialogVisible = false
        }
        this.getStaffList()
      } catch (error) {
        console.log(error)
      }
    },
    async close () {
      await this.$refs.ruleForm.resetFields()
    },
    //
    async update (obj) {
      this.title = '编辑人员'
      this.dialogVisible = true
      console.log(this.role)
      const res1 = await getRole()
      this.role = res1

      const res2 = await getArea(this.area)
      this.areaList = res2.currentPageRecords
      // console.log(this.areaList)
      // const oo = this.areaList.filter((item) => item.id === obj.regionId)
      // console.log(oo)
      this.ruleForm.userName = obj.userName
      this.ruleForm.roleId = obj.role.roleId

      this.ruleForm.mobile = obj.mobile
      this.ruleForm.regionId = obj.regionId
      this.ruleForm.status = obj.status
      this.ruleForm.image = obj.image
      this.ruleForm.regionName = obj.role.roleName
      this.ID = obj.id
      // console.log(this.ruleForm)
    }
  }
  // watch: {
  //   'ruleForm.regionId'(val) {
  //     const obj = this.areaList.filter((item) => item.id === val)
  //     this.ruleForm.regionName = obj[0].name
  //   }
  // }
}
</script>

<style scoped lang="scss">
:v-deep.avatar {
  width: 100px !important;
  height: 100px !important;
}
.search {
  width: 100%;
  height: 64px;
  background-color: #fff;

  padding: 12px;
  .el-input {
    width: 226px;
    height: 36px;
    margin-right: 10px;
  }
  .el-button {
    width: 86px;
    height: 36px;
  }
}
.label {
  .el-form-item {
    margin-top: 25px;
  }
}

.main {
  background-color: #fff;
  margin-top: 10px;
  height: 666px;
  width: 100%;
  padding: 20px;
  .title {
    margin-bottom: 20px;
    .el-button {
      border: 0;
    }
  }
  .body {
    margin-bottom: 20px;
  }
  .footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    span {
      color: #dbdfe5;
      font-size: 12px;
    }
    .el-button {
      background-color: #d5ddf8;
    }
  }
}
.el-link {
  margin-right: 5px;
  color: #a084ff;
}
::v-deep .el-table td.el-table__cell,
::v-deep .el-table th.el-table__cell.is-leaf {
  padding-bottom: 0 !important;
}
::v-deep .el-table th.el-table__cell > .cell {
  height: 40px;
  line-height: 40px;
  background: #f3f6fb;
}
::v-deep .el-form-item {
  margin-bottom: 0 !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
::v-deep .avatar-uploader {
  width: 100px;
  height: 100px;
}
::v-deep .avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  width: 100px;
  height: 100px;
  position: relative;
}
::v-deep .el-icon-plus:before {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
